<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/17 0017
 * Time: 下午 5:56
 */

namespace common\components\ActionsComponents;

use backend\components\LanguageTemplate;
use common\components\DataHelper;
use common\components\GlobalUrlComponent;

class UploadLocalAction extends CommonAction
{
    public $isBase64 = false;

    public $filename;

    public $uploadName;

    public $allowType = ["image/jpeg", "image/png", "image/x-icon"];

    //MB
    public $size = 2;

    public $saveAs;
    public $suffix;


    public static function getSuffixByMimeType($mimeType)
    {
        $ret = [
            "image/jpeg" => 'jpg',
            "image/png" => 'png',
            "image/x-icon" => 'ico'
        ];

        return $ret[$mimeType];
    }

    public function run()
    {
        $controller = $this->controller;
        if ( $this->isBase64 ) {
            $object = \Yii::$app->request->getBodyParam($this->uploadName);
            //这里需要注意 上传的base64图片 必须urlencode编码
            $object = urldecode($object);
            $object = str_replace([
                "data:image/png;base64,",
                "data:image/jpeg;base64,",
                "data:image/x-icon;base64,",
                " "
            ], "", $object);
            $object = base64_decode($object);#file_put_contents("D:/tmp.png", $object);

            $fileSize = strlen($object);
            $size = $this->size * 1024 * 1024;
            if ( $fileSize > $size ) {
                return  $controller->jsonResponse(
                    $controller::RESPONSE_FAILURE,
                    "上传文件最大为" . $this->size . "MB"
                );
            }

            //这里来校验一下指定的类型
            $fileInfo = finfo_open();
            $mime_type = finfo_buffer($fileInfo, $object, FILEINFO_MIME_TYPE);

            if ( !in_array($mime_type, $this->allowType) ) {
                return $controller->jsonResponse(
                    $controller::RESPONSE_FAILURE,
                    "错误的文件类型，只能上传" . implode(",", $this->allowType) . "[{$mime_type}]类型图片"
                );
            }

            if ( !$this->suffix ) {
                $this->suffix = self::getSuffixByMimeType($mime_type);
            }

            if ( !is_array($this->saveAs) ) {
                $this->saveAs = trim($this->saveAs, '/');
                $upPath = \Yii::getAlias("@static") . '/web' . "/" . $this->saveAs;
                $uploadApp = DataHelper::APP_STATIC;
            } else {
                $this->saveAs["path"] = ltrim($this->saveAs["path"]);
                $appPath = \Yii::getAlias("@" . $this->saveAs["app"]);
                $upPath = rtrim($appPath, "/") . "/web" . "/" . $this->saveAs["path"];
                $uploadApp = $this->saveAs["app"];
                $this->saveAs = $this->saveAs["path"];
            }

            if ( !$this->filename ) {
                $this->filename = uniqid();
            }
            $this->filename .= "." . $this->suffix;

            if ( !file_exists($upPath) ) {
                mkdir($upPath, 0777, true);
            }

            $uploadFile = rtrim($upPath, "/") . "/" .$this->filename;
            $ret = file_put_contents($uploadFile, $object);
            if ( !$ret ) {
                return $controller->jsonResponse(
                    $controller::RESPONSE_FAILURE,
                    "文件写入失败"
                );
            }

            $responseData = [
                "url" => GlobalUrlComponent::buildUrl($uploadApp, rtrim($this->saveAs, "/") . "/" . $this->filename),
                "path" => $uploadFile
            ];

        } else {
            $uploadRet = DataHelper::uploadFileAsLocal(
                $this->uploadName,
                $this->saveAs,
                false,
                $this->allowType,
                $this->size,
                $this->filename
            );

            if ( !$uploadRet["status"] ) {
                return  $controller->jsonResponse(
                    $controller::RESPONSE_FAILURE,
                    $uploadRet["msg"]
                );
            }

            $responseData = [
                "url" => $uploadRet["saveAs"]
            ];
        }

        $callbackRet = "";
        if ( $this->callback instanceof \Closure ) {
            $callback = $this->callback;
            if ( !($callbackRet = $callback($responseData)) ) {
                return  $controller->jsonResponse(
                    $controller::RESPONSE_FAILURE,
                    "上传失败"
                );
            }
        }

        if ( is_array($callbackRet) ) {
            $responseData = array_merge($responseData, $callbackRet);
        }

        return  $controller->jsonResponse(
            $controller::RESPONSE_SUCCESS,
            "操作成功",
            $responseData
        );
    }

}